package logic

import (
	"context"
	"errors"
	"share/common"

	"share/internal/svc"
	"share/pb/share"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetShareListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetShareListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetShareListLogic {
	return &GetShareListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// GetShareList 获取分享列表
func (l *GetShareListLogic) GetShareList(in *share.ShareListRequest) (*share.ShareListResponse, error) {
	orderByStr, ok := common.OrderMap[in.OrderBy]
	if !ok {
		return nil, errors.New("order by params error")
	}
	list, total, lastID, hasMore, err := l.svcCtx.ShareAggregationModel.GetShareList(l.ctx, in.UserId, in.Status, in.LastId, in.Limit, orderByStr)
	if err != nil {
		return nil, err
	}

	var data []*share.ShareInfo
	for _, v := range list {
		var expireTime int64
		if v.ExpireTime.Valid {
			val, _ := v.ExpireTime.Value()
			expireTime = val.(int64)
		}

		data = append(data, &share.ShareInfo{
			Id:         v.Id,
			UserId:     v.UserId,
			ShareLink:  v.ShareLink,
			ShareCode:  v.ShareCode,
			ShareType:  v.ShareType,
			Permission: v.Permission,
			ExpireType: v.ExpireType,
			ExpireTime: expireTime,
			Status:     v.Status,
			CreateAt:   v.CreateAt.Unix(),
			UpdateAt:   v.UpdateAt.Unix(),
			FolderIds:  v.FolderIDs,
			FileIds:    v.FileIDs,
		})
	}
	return &share.ShareListResponse{Total: total, LastId: lastID, HasMore: hasMore, List: data}, nil
}
